<template>
  <div class="index">
    <van-tabs v-model="active">
      <van-tab
        v-for="channel in channels"
        :key="channel.id"
        :title="channel.name"
      >
        <article-list :channel="channel.id"></article-list>
      </van-tab>
      <div
        class="bar-btn"
        v-show="$store.state.tokenInfo.token"
        @click="hShowChannelEdit"
      >
        <van-icon name="bars" />
      </div>
      <van-action-sheet
        v-model="isShowChannelEdit"
        title="编辑频道"
      >
        <div class="content">
          <channel-edit
            ref="channelEdit"
            :channels="channels"
            :curidx="active"
            @changechannel="hChangeChannel"
            @update-active="updateActive"
          ></channel-edit>
        </div>
      </van-action-sheet>
    </van-tabs>
  </div>
</template>

<script>
import ArticleList from './article.vue'
import { getChannels } from '../../api/channel.js'
import ChannelEdit from './channelEdit.vue'
export default {
  name: 'home',
  data () {
    return {
      channels: [], // 频道列表
      isShowChannelEdit: false, // 控制频道管理弹层
      active: 0
    }
  },
  components: {
    ArticleList, // 内容组件
    ChannelEdit // 频道管理组件
  },
  created () {
    // 获取用户频道信息
    this.hgetChannels()
  },
  methods: {
    hShowChannelEdit () {
      this.isShowChannelEdit = true
      // 判断ref是否有值，有则代表组件创建成功
      if (this.$refs.channelEdit) {
        this.$refs.channelEdit.isShowEdit = false
      }
    },
    // 用户频道信息获取封装
    async hgetChannels () {
      const res = await getChannels()
      this.channels = res.data.data.channels
      // console.log(res, this.channels)
    },

    hChangeChannel (curidx) {
      // 接收频道管理子组件传递的参数实现页面锁定为用户点击的频道页面
      this.active = curidx
      // console.log(curidx)
      // 关闭弹层
      this.isShowChannelEdit = false
    },
    // 更新active默认选中索引
    updateActive (idx) {
      // console.log(idx)
      if (this.active > idx) {
        this.active--
      }
    }
  }
}
</script>

<style scoped>
.bar-btn {
  position: fixed;
  right: 5px;
  top: 57px;
  display: flex;
  align-items: center;
  background-color: #fff;
  opacity: 0.8;
  z-index: 1;
  /* .van-icon-wap-nav {
    font-size: 20px;
  } */
}
</style>
